import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  Modal,
  message,
  Divider,
  Popconfirm,
  Select,
  InputNumber,
  Radio,
  TreeSelect,
  Tag,
  Switch,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import styles from '../search.less';
const { TextArea } = Input;
const FormItem = Form.Item;
const { Option } = Select;
const viewLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};

const dbType = ['mysql', 'oracle', 'teledb', 'pgsql'];
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/* eslint react/no-multi-comp:0 */
@connect(
  ({ scanTable, loading }) => ({
    scanTable,
    // loading: loading.models.scanTable,
    loading: loading.effects['scanTable/queryList'],
    loadingqueryListByTypeCode: loading.effects['database/queryListByTypeCode'],
  }),
  dispatch => ({
    queryListByTypeCode: e => dispatch({ type: 'database/queryListByTypeCode', payload: e }),
    dispatch,
  })
)
@Form.create()
class scanTable extends PureComponent {
  state = {
    modalVisible: false,
    formValues: {},
    selectedRows: [],
    text: {},
    levelList: [],
    typeCodeList: [],
    databaseList: [],
    showSensitiveInfo: true,
    datadbType: [],
  };

  columns = [
    {
      title: '数据库类型',
      dataIndex: 'dbType',
    },
    {
      title: '数据库名称',
      dataIndex: 'dbName',
    },
    {
      title: '表名',
      dataIndex: 'tableName',
    },
    {
      title: '数据分类',
      dataIndex: 'typeCode',
    },
    {
      title: '敏感级别',
      dataIndex: 'levelName',
      render: text => text && text.split(',').map(item => <Fragment>{item}&nbsp;&nbsp;</Fragment>),
    },
    {
      title: '敏感字段',
      dataIndex: 'sensLabel',
      render: text =>
        text &&
        text.split(',').map(item => (
          <Tag color="red" key={item}>
            {item}
          </Tag>
        )),
    },
    {
      title: '扫描时间',
      dataIndex: 'updateTime',
      render: text => <Fragment>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</Fragment>,
    },
    {
      title: '操作',
      width: 120,
      render: (text, props) => (
        <Fragment>
          <a onClick={() => this.handleDetailModalVisible(true, text)}>详情</a>
          <Divider type="vertical" />
          <ViewCols {...{ dbId: props.dbId, text, matchNums: this.state.showSensitiveInfo }}>
            <a>查看列</a>
          </ViewCols>
        </Fragment>
      ),
    },
  ];

  // 分页查询列表
  pageList(data, pageSize = 10, pageNum = 0) {
    const { dispatch } = this.props;
    const values = {
      dbType: data && data.dbType,
      dbName: data && data.dbName && data.dbName.split(',')[1], //逗号之后为dbName
      dbId: data && data.dbName && data.dbName.split(',')[0],
      tableName: data && data.tableName,
      levelName: data && data.levelName,
      typeCode: data && data.typeCode,
      matchNums: this.state.showSensitiveInfo == false ? '' : 0,
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'scanTable/queryList',
      payload: values,
    });
  }

  // 查询敏感级别
  selectLevelList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'scanTable/selectLevelList',
      callback: res => {
        this.setState({
          levelList: res.data.dataList,
        });
      },
    });
  }

  // 查询数据分类
  selectTypeCodeList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'scanTable/selectTypeCodeList',
      callback: res => {
        this.setState({
          typeCodeList: res.data,
        });
      },
    });
  }

  // 查询数据库
  selectDatabaseList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'scanTable/selectDatabaseList',
      callback: res => {
        this.setState({
          databaseList: res.data.dataList,
        });
      },
    });
  }

  componentDidMount() {
    this.pageList();
    this.selectTypeCodeList();
    this.selectLevelList();
    this.selectDatabaseList();
    this.props.queryListByTypeCode({ dataDictTypeCode: 'dbType' }).then(res => {
      if (res.rescode == 200) {
        this.setState({ datadbType: res.data ? res.data.dataList || [] : [] });
      } else {
        Modal.error({ title: '获取数据库类型失败' });
      }
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      });
      //点击查询
      this.pageList(fieldsValue);
    });
  };

  // 详情
  handleDetailModalVisible = (flag, text) => {
    this.setState({
      detailModalVisible: !!flag,
      detailsData: text,
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  switchChange = checked => {
    this.setState({ showSensitiveInfo: checked }, () => {
      this.pageList();
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { levelList, typeCodeList, databaseList } = this.state;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="数据库类型">
              {getFieldDecorator('dbType')(
                <Select placeholder="请选择" allowClear>
                  <Option value="">全部</Option>
                  {this.state.datadbType.map(item => (
                    <Option value={item.value} key={item.value}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="数据库名称">
              {getFieldDecorator('dbName')(
                <Select
                  placeholder="请选择"
                  allowClear
                  // onFocus={()=>this.selectDatabaseList()}
                >
                  <Option value="">全部</Option>
                  {databaseList &&
                    databaseList.length &&
                    databaseList.map(v => {
                      return (
                        <Option value={`${v.dbId},${v.dbName}`} key={v.dbId}>
                          {v.dbName}
                        </Option>
                      );
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="表名">
              {getFieldDecorator('tableName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;&nbsp;敏感级别">
              {getFieldDecorator('levelName')(
                <Select
                  placeholder="请选择"
                  allowClear
                  // onFocus={()=>this.selectLevelList()}
                >
                  <Option value="">全部</Option>
                  {levelList &&
                    levelList.length &&
                    levelList.map(v => {
                      return (
                        <Option value={v.name} key={v.level}>
                          {v.name}
                        </Option>
                      );
                    })}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;&nbsp;数据分类">
              {getFieldDecorator('typeCode')(
                <TreeSelect
                  showSearch
                  style={{ width: '100%' }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  showCheckedStrategy="SHOW_PARENT"
                  searchPlaceholder="关键字"
                  allowClear
                  placeholder="请选择"
                  // onFocus={()=>this.selectTypeCodeList()}
                >
                  {loopTree && loopTree(typeCodeList)}
                </TreeSelect>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  render() {
    const {
      scanTable: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, text, detailModalVisible, detailsData } = this.state;
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };
    return (
      <Fragment>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <Switch
              checkedChildren="仅含敏感数据"
              unCheckedChildren="所有数据"
              onChange={this.switchChange}
              checked={this.state.showSensitiveInfo}
              style={{ marginBottom: 16 }}
            />
            <br />
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
              hideRowSelection
            />
          </div>
        </Card>
        {detailModalVisible ? (
          <Details
            {...detailsMethods}
            detailModalVisible={detailModalVisible}
            detailsData={detailsData}
          />
        ) : null}
      </Fragment>
    );
  }
}

//查看详情弹窗
class Details extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const { detailModalVisible, handleDetailModalVisible, detailsData } = this.props;
    return (
      <Modal
        destroyOnClose
        width={640}
        title="查看详情"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>
            返回
          </Button>,
        ]}
        className={styles.viewMore}
      >
        <Row>
          <Col md={24}>
            <FormItem {...viewLayout} label="数据库类型">
              {detailsData.dbType}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem {...viewLayout} label="数据库名称">
              {detailsData.dbName}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem {...viewLayout} label="表名">
              {detailsData.tableName}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem {...viewLayout} label="敏感级别">
              {detailsData.levelName && detailsData.levelName.replace(/,/g, '；')}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem {...viewLayout} label="敏感字段">
              {detailsData.sensLabel && detailsData.sensLabel.replace(/,/g, '；')}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem {...viewLayout} label="数据分类代码">
              {detailsData.typeCode && detailsData.typeCode.replace(/,/g, '；')}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem {...viewLayout} label="数据分类名称">
              {detailsData.typeName && detailsData.typeName.replace(/,/g, '；')}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem {...viewLayout} label="扫描时间">
              {moment(detailsData.updateTime).format('YYYY-MM-DD HH:mm:ss')}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    );
  }
}

//查看列弹窗
@connect(
  state => ({
    dataColumn: state.scanTable.dataColumn,
    loadingqueryColumnList: state.loading.effects['scanTable/queryColumnList'],
  }),
  dispatch => ({
    queryColumnList: e => dispatch({ type: 'scanTable/queryColumnList', payload: e }),
    saveColumn: e => dispatch({ type: 'scanTable/saveColumn', payload: e }),
  })
)
class ViewColsShell extends PureComponent {
  state = {
    selectedRows: [],
  };
  colColumns = [
    {
      title: '列名',
      dataIndex: 'columnName',
    },
    {
      title: '敏感字段',
      dataIndex: 'label',
      render: text => text && <Tag color="red">{text}</Tag>,
    },
    {
      title: '列备注',
      dataIndex: 'columnRemark',
    },
    {
      title: '采样数据',
      dataIndex: 'remark',
      ellipsis: 'true',
    },
  ];
  // 数据库列名-分页查询列表
  pageColsList = (res = {}, pageSize = 10, pageNum = 0) => {
    const values = {
      dbId: this.props.dbId,
      tableName: this.props.text.tableName,
      matchNums: this.props.matchNums == false ? '' : 0,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    this.props.queryColumnList(values);
  };
  componentDidMount() {
    this.pageColsList();
  }

  componentWillUnmount() {
    this.props.saveColumn({
      dataList: [],
      pageNum: 0,
      pageSize: 0,
      totalCount: 0,
    });
  }

  handleStandardColumnChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageColsList(formValues, pagination.pageSize, pagination.current - 1);
  }
  render() {
    const { dataColumn } = this.props;
    return (
      <TableList
        bordered
        className={styles.tdPadding}
        selectedRows={this.state.selectedRows}
        loading={this.props.loadingqueryColumnList}
        data={dataColumn}
        columns={this.colColumns}
        onChange={this.handleStandardColumnChange.bind(this)}
        rowKey={record => record.id}
        hideRowSelection
      />
    );
  }
}
class ViewCols extends PureComponent {
  constructor(props) {
    super(props);
  }
  state = {
    viewColsModalVisible: false,
  };
  handleViewColsModalVisible = flag => {
    this.setState({
      viewColsModalVisible: !!flag,
    });
  };

  render() {
    const { text } = this.props;
    return (
      <>
        <Modal
          destroyOnClose
          width={800}
          title="查看列"
          visible={this.state.viewColsModalVisible}
          onCancel={() => this.handleViewColsModalVisible(false)}
          footer={[
            <Button key="back" type="primary" onClick={() => this.handleViewColsModalVisible()}>
              返回
            </Button>,
          ]}
          // className={styles.viewMore}
        >
          <div style={{ marginBottom: 16 }}>表名：{this.props.text.tableName}</div>
          <ViewColsShell {...this.props} />
        </Modal>
        <span onClick={() => this.handleViewColsModalVisible(true)}>{this.props.children}</span>
      </>
    );
  }
}

export default scanTable;

const loopTree = data => {
  return (
    data &&
    data.map(item => {
      if (item.children) {
        return (
          <TreeSelect.TreeNode value={item.typeCode} title={`${item.typeCode}${item.typeName}`}>
            {loopTree(item.children)}
          </TreeSelect.TreeNode>
        );
      }
      return (
        <TreeSelect.TreeNode value={item.typeCode} title={`${item.typeCode}${item.typeName}`} />
      );
    })
  );
};
